package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;


//这个拦截器，拦截的是所有请求，属于第一层拦截器
//在这个拦截器中，通过redis查询用户是否存在，如果存在，放入ThreadLocal中，并且更新redis中该用户的过期时间，变回初始值
//不管存不存在用户，都放行
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token))
            return true;
        //通过redis获取token对应的对象
        String redis_key=RedisConstants.LOGIN_USER_KEY+token;
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(redis_key);
        if (entries.isEmpty())
            return true;
        //将用户对象放到threadlocal
        UserDTO userDTO = BeanUtil.fillBeanWithMap(entries, new UserDTO(), false);
        UserHolder.saveUser(userDTO);
        //更新过期时间
        stringRedisTemplate.expire(redis_key,RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //ThreadLocal 避免内存泄漏
        UserHolder.removeUser();
    }
}
